package util;

import java.sql.*;

public class DataBaseConnection {
	public static Connection dataBaseConnection() {
		Connection conn = null;
		try {
    		Class.forName("com.mysql.jdbc.Driver");
    		conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/yoga??useUnicode=true&characterEncoding=utf-8", "root", "shw");
    		//System.out.println("成功加载MySQL驱动程序");  
   
        } catch (SQLException e) {  
            e.printStackTrace();  
        } catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return conn;
	}
	
	public static String queryDataBase(String sql, int type) {
		Connection conn = dataBaseConnection();
		String result = null;
		ResultSet rs = null;
		Statement stmt = null;
		try {
			stmt = conn.createStatement();
			rs = stmt.executeQuery(sql);//创建数据对象
			while (rs.next()){     //"0"为字符串，“1”为整数
	        	if (type == 0) {
	        		result = String.valueOf(rs.getInt(1)) + ' ';
	        	} else if (type == 1) {     
	        		result = rs.getString(1);
	        	}
	            
	        }
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally {
			
	        try {
				stmt.close();
				rs.close();
				conn.close();
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
	        
		}
		return result;
	}
       
	
	public static boolean hasRow(String sql) {
		Connection conn = dataBaseConnection();
    	boolean flag = false;
    	Statement stmt = null;
    	ResultSet rs = null;
    	try {
    		stmt = conn.createStatement();
            rs = stmt.executeQuery(sql);//创建数据对象
           if (rs.next()){
                flag = true;
                }
        } catch (SQLException e) {  
            //System.out.println("插入数据库时出错：");  
            e.printStackTrace();  
        } finally {  
			try {
				 	rs.close();
		            stmt.close();
		            conn.close();

			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
        } 
    	return flag;
	}

	public static void updateDataBase(String sql) {
		// TODO Auto-generated method stub
		Connection conn = dataBaseConnection();
		PreparedStatement statement;
		try {
			statement = conn.prepareStatement(sql);
			statement.executeUpdate();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally {
			try {
				conn.close();
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}

	}


}
